package com.wiscamp.ninechapters.accounts.infrastructure.configuration;

import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Objects;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryFifth",
        transactionManagerRef = "transactionManagerFifth",
        basePackages = {"com.wiscamp.ninechapters.accounts.infrastructure.mappers"}) //设置Repository所在位置
public class FifthDatabaseConfig {

    @Autowired
    @Qualifier("fifthDataSource")
    private DataSource fifthDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "entityManagerFifth")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        System.out.println("Loading accounts database.");
        return Objects.requireNonNull(entityManagerFactoryFifth(builder).getObject()).createEntityManager();
    }

    @Bean(name = "entityManagerFactoryFifth")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryFifth(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(fifthDataSource)
                .properties(getVendorProperties())
                .packages("com.wiscamp.ninechapters.accounts.infrastructure.po") //设置实体类所在位置
                .persistenceUnit("fifthPersistenceUnit")
                .build();
    }

    private Map<String, String> getVendorProperties() {
        return jpaProperties.getProperties();
    }

    @Bean(name = "transactionManagerFifth")
    PlatformTransactionManager transactionManagerFifth(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(entityManagerFactoryFifth(builder).getObject()));
    }
}
